from django.shortcuts import get_object_or_404, render_to_response, Http404, HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from apps import files
from django.views.decorators.csrf import csrf_protect
from django.contrib.contenttypes.models import ContentType

from apps.management import Management

import logging
logger = logging.getLogger('pet.apps.files.manage')

@csrf_protect
@login_required
def manage(request, TheCourseParticipant, course, content_type, object_pk, options = None):
    logger.fxn_entry("TheCourseParticipant %s, course %s, content_type %s, object_pk %s, options %s",TheCourseParticipant, course, content_type, object_pk, options)
    ModelCT = get_object_or_404(ContentType,pk=content_type)
    Object = ModelCT.get_object_for_this_type(pk=object_pk)
    qs = files.get_model().objects.filter(content_type=ModelCT, object_pk=object_pk)
    
    fileforms = []
    if request.method == "POST":
        Error = False
        if "DeleteFile" in request.POST:
            return delete(request,TheCourseParticipant,course,request.POST['DeleteFile'])
        for file in qs:
            form = files.forms.FileEditForm(data=request.POST,files=request.FILES,instance=file,prefix="file%d"%file.id)
            fileforms.append(form)
            if form.is_valid():
                if form.has_changed():
                    form.save()
                else: logger.form_unchanged("Fileform unchanged")
            else: Error = True; logger.debug("Fileform invalid %s", form)
    else:
        for file in qs:
            fileforms.append(files.forms.FileEditForm(instance=file,prefix="file%d"%file.id))
            
    return render_to_response('files/manage.html',{'Object':Object,'Forms':fileforms,'options':options.split(';') if options else None},context_instance=RequestContext(request))
Management.register_interface("Files","INSTRUCTOR;ASSISTANT;SUPERUSER","manage",manage,indirect=True)

@csrf_protect
@login_required
def delete(request, TheCourseParticipant, course, file_id):
    file = get_object_or_404(files.get_model(), pk=file_id)
    if not request.user.is_superuser and TheCourseParticipant.status != "INSTRUCTOR" and TheCourseParticipant.status != "ASSISTANT":
        logger.http404('User %s attempting to delete file %s',request.user, file)
        raise Http404
    if request.method != 'POST' or not 'next' in request.POST:
        logger.http404('Non-POST or next missing from POST data %s' % request.POST)
        raise Http404
    next = request.POST['next']
    
    if 'DeleteConfirmation' in request.POST:
        file.delete()
        messages.info(request,"File successfully deleted")
        logger.fxn_exit('Returning to %s after deleting file',next)
        return HttpResponseRedirect(next)

    # Render a form otherwise
    else:
        logger.fxn_exit('Returning delete confirmation')
        return render_to_response('files/delete.html',
            {'file': file, "next": next},
            context_instance=RequestContext(request)
        )
Management.register_interface("Files","INSTRUCTOR;ASSISTANT;SUPERUSER","delete",delete,indirect=True)